import router from "./index";
import useMain from "@/stores/useMain.js";
import userUser from "@/stores/userUser";
import {TokenUtil} from "@lowcode/jpaas-base-lib";

/*进度条*/
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false });
import {
    getState,
    getQueryVariable,
    client_id,
    getAuthorizeUri
} from "@/assets/js/loginPublic.js";
import rxAjax from '@/assets/js/ajax.js';
import componentLang from "@/language/lang/impl/layouts/compomentLang";
//不需要登录访问的白名单路由名称集合。
const whiteList = ['login','PlatformLogin','register', 'registerResult', 'forget', 'Signature',
    'singlelogin', 'tenantLogin','qrcodeLogin','ticketLogin','mobileCodeLogin'];

function isInWeChatWork() {
    // 企业微信的用户代理中包含 'wxwork'
    const ua = navigator.userAgent.toLowerCase();
    if (ua.includes('wxwork')) {
        return true; // 企业微信
    }
    if (ua.includes('dingtalk')) {
        return true; // 钉钉
    }
    return false; // 都不是
}
router.beforeEach((to, from, next) => {
    NProgress.start()
    let loginUrl = 'login'
    if (isInWeChatWork()) {
        //企业微信
        loginUrl = 'PlatformLogin'
    } else {
        //普通浏览器
        loginUrl = 'login'
    }
    const token = TokenUtil.getToken();
    const store = useMain()
    const userStore = userUser();
    if(to.path.indexOf('/null/') > -1){
        next({name:loginUrl})
        return;
    }
    if(["qrcodeLogin","mobileCodeLogin","applogin"].includes(to.name)){
        next()
        NProgress.done()
        return
    }
    if(token){
        if(userStore.isFirstLogin){
            if(to.name !=="changePassword"){
                next({path: '/changePassword'});
            }else {
                next();
            }
            NProgress.done()
        } else if(store.logined){
            next();
            NProgress.done()
        } else {
            store.generateRoutes().then(res=>{
                let redirect = decodeURIComponent(from.query.redirect || to.path);
                if (to.path === redirect) {
                    // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                    next({...to, replace: true})
                } else if(to.path === '/'){
                    next({path:'appHome'})
                } else {
                    // 跳转到目的路由
                    location.href=redirect;
                }
                NProgress.done()
            });
        }
    }else {
        let portal = import.meta.env.JPAAS_APP_PORTAL;
        if (whiteList.includes(to.name) && (to.name==loginUrl && portal !== 'true')) {
            next();
            NProgress.done()
            return;
        }
        if(portal !== 'true') {
            next({name: loginUrl})
            NProgress.done()
        }else {
            //1.先判断是否有state，如果没有证明第一次进入，则跳转到登录页，否则就是回调页
            let queryState = getQueryVariable('state');
            if (queryState) {
                let localState = sessionStorage.getItem("state");
                //判断state防止CSRF攻击
                if (localState !== queryState) {
                    let state = getState();
                    sessionStorage.setItem("state", state);
                    window.location = getAuthorizeUri(state,client_id,function(authorizeUri,data){
                        sessionStorage.setItem("visitUri", data.redirect_uri);
                        window.open(authorizeUri, '_self');
                    });
                } else {
                    //进入回调页面
                    //url获取code
                    let code = getQueryVariable('code');
                    const url = "/api-user/user/org/token/getTokenByCode" + "?code=" + code + '&clientId=' + client_id;
                    rxAjax.get(url).then(resp => {
                        TokenUtil.setToken(resp.access_token);
                        window.location = sessionStorage.getItem('visitUri');
                    }).catch((err) => {
                        console.log(err.response)
                    })
                }
            } else {
                let state = getState();
                sessionStorage.setItem("state", state);
                //构建调整url
                getAuthorizeUri(state,client_id,function(authorizeUri,data){
                    sessionStorage.setItem("visitUri", data.redirect_uri);
                    window.open(authorizeUri, '_self');
                });
            }
        }
    }
})
